# This is a sample Python script.
import json
import time

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Content-Type': 'application/json',
    "Accept": "application/json",
}
def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.

def save_to_file(data, file_index):
    with open(f"parsed_data_{file_index}.txt", "w", encoding="utf-8") as f:
        for item in data:
            f.write(
                f"{item['搜索词']}\n")


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    try:

        # 获取用户输入的两个数字
        num1 = int(input("请输入开始排名： "))
        num2 = int(input("请输入结束排名: "))

        data_amount = int(input("请输入每个文件的数据量: "))

        # 数据来源
        data = [
            {
                "country": "美国",
                "country_code": "us"
            },
            {
                "country": "法国",
                "country_code": "fr"
            },
            {
                "country": "墨西哥",
                "country_code": "mx"
            },
            {
                "country": "英国",
                "country_code": "uk"
            },
            {
                "country": "德国",
                "country_code": "de"
            },
            {
                "country": "意大利",
                "country_code": "it"
            },
            {
                "country": "西班牙",
                "country_code": "es"
            },
            {
                "country": "加拿大",
                "country_code": "ca"
            },
            {
                "country": "日本",
                "country_code": "jp"
            }
        ]

        # 打印可选国家
        print("请选择一个国家：")
        for i, item in enumerate(data, 1):
            print(f"{i}. {item['country']}")

        # 获取用户输入的选择
        choice = int(input("请输入对应国家的序号: "))
        country_code = 'us'
        # 获取对应的国家代码
        if 1 <= choice <= len(data):
            selected_country = data[choice - 1]
            country = selected_country['country']
            country_code = selected_country['country_code']
            print(f"您选择的国家是 {country}，其国家代码是 {country_code}")
        else:
            print("无效的选择，请输入正确的序号。")
        send_data = {"word":"","country":country_code,"ranking_this_week":[num1,num2],"fluctuation_range":[],"word_len_range":[],"click_range":[],"conversion_range":[],"ne_word":"","top3_brand":"","top3_category":"","fluctuation_use_abs":1,"page":{"size":200,"num":1,"sorts":[{"condition":"new_rank","order":1}]}}

        json_data = json.dumps(send_data)
        resdata = requests.post('https://api.amz123.com/search/v1/hotwords/search',headers=headers ,data=json_data)
        resdata = resdata.json()
        # rows = resdata['data']['rows']
        total = resdata['data']['total']
        pagetotal = int(total / 200)
        print('总页数为::',pagetotal)
        pages = str(input("请输入要抓取的页数,如果输入 ALL 代表全部抓取"))
        file_index = 1
        parsed_data = []


        forNums = pages
        if pages == 'ALL':
            forNums = pagetotal
        else:
            if int(forNums) >= pagetotal:
                forNums = pagetotal
            if int(forNums) == 0:
                forNums = 1

        for i in range(1,int(forNums)+1):
            print(f'正在爬取第{i}页...')
            send_data_total = {"word": "", "country": country_code, "ranking_this_week": [num1, num2], "fluctuation_range": [],
                         "word_len_range": [], "click_range": [], "conversion_range": [], "ne_word": "", "top3_brand": "",
                         "top3_category": "", "fluctuation_use_abs": 1,
                         "page": {"size": 200, "num": i, "sorts": [{"condition": "new_rank", "order": 1}]}}
            time.sleep(2)
            resdata = requests.post('https://api.amz123.com/search/v1/hotwords/search', headers=headers, data= json.dumps(send_data_total))
            resdata = resdata.json()
            rows = resdata['data']['rows']
            for row in rows:
                parsed_row = {
                    "搜索词": row["word"],
                    "本周排名": row["new_rank"],
                    "上周排名": row["old_rank"],
                    "涨跌幅度": row["fluctuation"]
                }
                parsed_data.append(parsed_row)
                if len(parsed_data) >= data_amount:
                    save_to_file(parsed_data, file_index)
                    parsed_data = []
                    file_index += 1

        if parsed_data:
                save_to_file(parsed_data, file_index)
    except:
        print("程序出错，请重新启动...")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
